import json
from copy import deepcopy

from src.tools.chain import gen_chain
from src.tools.dms_operator import dmsoperator
from src.tools.information_exchange import pub_gen
from src.tools.split_string import split_sub_string
from src.translation_file.prompt import Prompt
from src.translation_file.re_translation_string import re_tran_string


class TranslationFile:

    def __init__(self):
        self.prompt = Prompt()

    # 翻译每一段内容
    def translation_file_para(self, tran_language: str, para_text: dict, task_id:str, file: dict):
        tran_query = self.prompt.translation_prompt(text=json.dumps(para_text, ensure_ascii=False),
                                                    language=tran_language)
        tran_jsontext = gen_chain(tran_query)
        print(tran_jsontext)
        tran_jsontext = re_tran_string(tran_jsontext)
        print(tran_jsontext)
        try:
            tran_text_dict = json.loads(tran_jsontext)
        except Exception as e:
            tran_text_dict = {"text":" "}
            print(str(e))
        if tran_text_dict.get("text"):
            contentsss = para_text.get("text")
            print(f"原文send: {contentsss}")
            pub_gen(task_id, para_text.get("text"), file.get("docId"), file.get("taskDocId"))
            contentsss = tran_text_dict.get("text")
            print(f"译文send: {contentsss}")
            pub_gen(task_id, tran_text_dict.get("text"), file.get("docId"), file.get("taskDocId"))
        return tran_text_dict.get("text")

    def translation_file(self, tran_language: str, file: dict, task_id:str):
        file_realpath = file.get("realPath")
        # 翻译文件是pdf就需要先转换为word
        if file_realpath.endswith(".pdf"):
            file_jsondata = dmsoperator.get_pdf2jsonfile(file_realpath)
        else:
            file_jsondata = dmsoperator.get_jsonfile(file_realpath)
        # 双语文件修改
        file_pubinfo = {
            "filePath": file_jsondata["filePath"],
            "editInfos": []
        }
        # 单语文件修改
        single_file_pubinfo = deepcopy(file_pubinfo)

        # 翻译段落
        for para in file_jsondata["paragraphInfos"]:
            # 空格数字跳过
            if para["text"] == "" or para["text"].isspace() or para["text"].isdigit():
                continue
            # 组合翻译文本
            para_text = ""
            for textinfo in para["textInfos"]:
                if textinfo["subSuperscript"] == 2:
                    para_text += f'<sub>{textinfo["text"]}</sub>'
                else:
                    para_text += textinfo["text"]

            para_dict = {
                "index": para["index"],
                "text": para_text
            }
            tran_text = self.translation_file_para(tran_language, para_dict, task_id, file)
            # 分割下标字符串
            tran_paratext_list = split_sub_string(tran_text)
            tran_paras = []
            single_tran_paras = []
            for tran_index, tran_paratext in enumerate(tran_paratext_list):
                # 双语第一段要带有编号，其余不需要
                if tran_index == 0:
                    tran_paratext_dict = {
                        "paragraphChildIndex": tran_index,
                        "paraChildType": 0,
                        "content": para["listText"] + tran_paratext.get("content"),
                        "subSuperScript": tran_paratext.get("subSuperScript")
                    }
                    tran_paras.append(tran_paratext_dict)
                    single_tran_paratext_dict = {
                        "paragraphChildIndex": tran_index,
                        "paraChildType": 0,
                        "content": tran_paratext.get("content"),
                        "subSuperScript": tran_paratext.get("subSuperScript")
                    }
                    single_tran_paras.append(single_tran_paratext_dict)
                else:
                    tran_paratext_dict = {
                        "paragraphChildIndex": tran_index,
                        "paraChildType": 0,
                        "content": tran_paratext.get("content"),
                        "subSuperScript": tran_paratext.get("subSuperScript")
                    }
                    tran_paras.append(tran_paratext_dict)
                    single_tran_paras.append(tran_paratext_dict)

            tran_para_dict = {
                "index": para["index"],
                "sectionIndex": para["sectionIndex"],
                "bodyChildIndex": para["bodyChildIndex"] + 1,
                "operationType": 1,
                "paragraphInfo": {
                    "paragraphChildInfos":tran_paras
                }
            }
            single_tran_para_dict = {
                "index": para["index"],
                "sectionIndex": para["sectionIndex"],
                "bodyChildIndex": para["bodyChildIndex"],
                "operationType": 1,
                "paragraphInfo": {
                    "paragraphChildInfos":single_tran_paras,
                    "referenceParagraphType": 2
                }
            }
            dele_single_tran_para_dict = {
                "index": para["index"],
                "sectionIndex": para["sectionIndex"],
                "bodyChildIndex": para["bodyChildIndex"],
                "operationType": 2
            }
            file_pubinfo["editInfos"].append(tran_para_dict)
            single_file_pubinfo["editInfos"].append(single_tran_para_dict)
            single_file_pubinfo["editInfos"].append(dele_single_tran_para_dict)

        # 翻译表格
        for table in file_jsondata["tableInfos"]:
            table_dict = {
                        "index": table["index"],
                        "sectionIndex": table["sectionIndex"],
                        "bodyChildIndex": table["bodyChildIndex"],
                        "operationType": 0,
                        "tableInfo":{
                            "cellEditInfos": []
                        }
                    }
            single_table_dict = deepcopy(table_dict)
            for cell in table ["tableCellInfos"]:
                cell_dict = {
                    "rowIndex": cell["rowIndex"],
                    "columnIndex": cell["columnIndex"],
                    "cellChildInfos": []
                }
                single_cell_dict = deepcopy(cell_dict)
                for para in cell["paragraphInfos"]:
                    # 跳过空格数字
                    if para["text"] == "" or para["text"].isspace() or para["text"].isdigit():
                        continue

                    para_text = ""
                    for textinfo in para["textInfos"]:
                        if textinfo["subSuperscript"] == 2:
                            para_text += f'<sub>{textinfo["text"]}</sub>'
                        else:
                            para_text += textinfo["text"]

                    para_dict = {
                        "index": para["index"],
                        "text": para_text
                    }
                    tran_text = self.translation_file_para(tran_language, para_dict, task_id, file)

                    tran_paratext_list = split_sub_string(tran_text)
                    tran_paras = []
                    single_tran_paras = []
                    for tran_index, tran_paratext in enumerate(tran_paratext_list):
                        if tran_index == 0:
                            tran_paratext_dict = {
                                "paragraphChildIndex": tran_index,
                                "paraChildType": 0,
                                "content": para["listText"] + tran_paratext.get("content"),
                                "subSuperScript": tran_paratext.get("subSuperScript")
                            }
                            tran_paras.append(tran_paratext_dict)
                            single_tran_paratext_dict = {
                                "paragraphChildIndex": tran_index,
                                "paraChildType": 0,
                                "content": tran_paratext.get("content"),
                                "subSuperScript": tran_paratext.get("subSuperScript")
                            }
                            single_tran_paras.append(single_tran_paratext_dict)
                        else:
                            tran_paratext_dict = {
                                "paragraphChildIndex": tran_index,
                                "paraChildType": 0,
                                "content": tran_paratext.get("content"),
                                "subSuperScript": tran_paratext.get("subSuperScript")
                            }
                            tran_paras.append(tran_paratext_dict)
                            single_tran_paras.append(tran_paratext_dict)


                    tran_para_dict = {
                        "index": para["index"] + 1,
                        "sectionIndex": para["sectionIndex"],
                        "bodyChildIndex": para["bodyChildIndex"],
                        "operationType": 1,
                        "paragraphInfo": {
                            "paragraphChildInfos":tran_paras,
                            "referenceParagraphType": 1
                        }
                    }
                    single_tran_para_dict = {
                        "index": para["index"],
                        "sectionIndex": para["sectionIndex"],
                        "bodyChildIndex": para["bodyChildIndex"],
                        "operationType": 1,
                        "paragraphInfo": {
                            "paragraphChildInfos":single_tran_paras,
                            "referenceParagraphType": 2
                        }
                    }
                    # 删除段落
                    dele_single_tran_para_dict = {
                        "index": para["index"],
                        "sectionIndex": para["sectionIndex"],
                        "bodyChildIndex": para["bodyChildIndex"],
                        "operationType": 2
                    }
                    cell_dict["cellChildInfos"].append(tran_para_dict)
                    single_cell_dict["cellChildInfos"].append(single_tran_para_dict)
                    single_cell_dict["cellChildInfos"].append(dele_single_tran_para_dict)
                table_dict["tableInfo"]["cellEditInfos"].append(cell_dict)
                single_table_dict["tableInfo"]["cellEditInfos"].append(single_cell_dict)
            file_pubinfo["editInfos"].append(table_dict)
            single_file_pubinfo["editInfos"].append(single_table_dict)

        print("-" * 200)
        file_pubinfo_json = json.dumps(file_pubinfo, indent=4, ensure_ascii=False)
        print(file_pubinfo_json)
        # # 保存修改的json文件
        # edit_SOPjsonfile_path = f"翻译.json"
        # with open(edit_SOPjsonfile_path, "w", encoding="utf-8") as f:
        #     f.write(file_pubinfo_json)
        print("-" * 200)

        tran_res = dmsoperator.post_edit_file_v2(file_pubinfo)
        single_tran_res = dmsoperator.post_edit_file_v2(single_file_pubinfo)
        # 以pdf结尾就转为pdf文件返回
        if file_realpath.endswith(".pdf"):
            return [dmsoperator.get_docx2pdf(tran_res["data"]), dmsoperator.get_docx2pdf(single_tran_res["data"])]
        else:
            return [tran_res["data"], single_tran_res["data"]]
